import axios from 'axios'
import type { Method } from 'axios'
import { member } from '@/store'
import { message } from '@/components/XtxUI/Message'
// 创建 axios 实例
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
  timeout: 50000,
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    const Member = member() //当前行不建议写在script中，不明确代码执行顺序导致获取不到pinia数据
    const { token } = Member.userInfo
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么

    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    // 对响应错误做点什么
    console.log(`output->error.message`, error.message)
    if (error.message === 'Network Error') {
      message({ type: 'warn', text: '网络开小差了，请检查网络后重试~' })
    } else {
      message({ type: 'warn', text: error.message })
    }
    return Promise.reject(error)
  }
)

export const http = <T>(url: string, method: Method, obj?: object) => {
  return instance<{
    code: string
    msg: string
    result: T
  }>({
    url,
    method,
    [method.toLocaleUpperCase() === 'GET' ? 'params' : 'data']: obj,
  })
}

export default instance
